package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author DASK
 * @date 2020/4/2 12:55
 * @description //TODO 数据库连接池
 */
public class MySQLPool {
    private static final int DEFAULT_SIZE = 2;//默认线程池大小
    private static final int MAX_SIZE = 5;//最大线程池大小
    //这里为了防止反复创建套接字连接，这里使用数据库连接池管理
    private static List<Connection> list = Collections.synchronizedList(new ArrayList<>());

    //加载mysql驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void initPool() {
        try {
            for (int i = 0; i < 2; i++) {
                Connection connection = createConnection();
                list.add(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //创建连接
    private static Connection createConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/library_sys", "root", "113911");
    }

    //获取一个可用连接
    public static Connection getAvailableConnection() {
        for (Iterator<Connection> it = list.iterator(); it.hasNext(); ) {
            Connection con = it.next();
            //验证连接是否超时
            try {
                //无效则创建新的连接,删除无效连接
                if (!con.isValid(2000)) {
                    con.close();
                    it.remove();
                    if (list.size() <= MAX_SIZE) {
                        Connection connect = createConnection();
                        list.add(connect);
                        return connect;
                    } else {
                        return null;
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return con;
        }
        return null;
    }


    //释放连接池
    public static void releasePool() {
        for (Connection connection : list) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        list.clear();
    }

}
